#include "component.h"
#include "local_main.h"
#include "menu.h"
#include "local_lock.h"
#include "time.h"
#include "local_sub.h"

#ifndef KOS_PARAM_USERS_QTY_FINGER
#define KOS_PARAM_USERS_QTY_FINGER 10
#endif

#define LOCAL_MAIN_LOG(format, ...) OSAL_LOG(C_GREEN format C_NONE, ##__VA_ARGS__)
#define __LOCAL_MAIN_LOG(format, ...) __OSAL_LOG(C_GREEN format C_NONE, ##__VA_ARGS__)

TimerHandle_stu_t local_sub_timer = NULL; //报警任务定时器
extern uint8_t asteriskKeyTimes;		//星键输入次数 TODO:临时测试措施
extern uint8_t get_fpt_sleep_flag(void);
extern void set_fpt_sleep_flag(uint8_t flag);
extern void Finger_send_cmd_pack(uint8_t cmd, uint8_t *pbuf, uint16_t len);
/**
 * @brief  复位NV里面所有数据
 *
 * @note   恢复出厂设置时调用
 */

ErrorStatus Local_NvReset(uint8_t reset)
{
    uint8_t nvInitFlag;
    OSAL_NvRead(SYS_OFFSET(nvInitFlag), &nvInitFlag, 1);
    LOCAL_MAIN_LOG("nvInitFlag:%#X\r\n", nvInitFlag);
    // nvInitFlag =0;
    if (nvInitFlag != NV_INIT_FLAG)
    {
        NvSystemParam_stu_t sys_data;
        memset(&sys_data, 0, sizeof(NvSystemParam_stu_t));
        sys_data.nvInitFlag = NV_INIT_FLAG;                    // 初始化标志
        sys_data.sys_flag = 0;                                 //防撬报警标志 布防报警标志 布防状态 反锁状态 老化状态 机械钥匙报警标志 自动模式 安全模式
        sys_data.verifyErrCount = 0;                           // 验证失败的次数
        sys_data.verifyErrTime = 0;                            // 验证失败的时间
        sys_data.systemLockedTime = 0;                         // 系统锁定的时间
        sys_data.openLockTimes = 0;                            // 开锁次数
        sys_data.powerSavingMode = POWER_SAVING_CLOSE;         // 节能模式 视频功能默认关闭
        sys_data.lock_type = APP_LOCK_TYPE;                    // 锁类型
        sys_data.func_code = FUNC_CODE;                        // 功能集
        sys_data.default_language = DEFAULT_LANGUAGE;          // 默认语言（恢复出厂设置后的语言）
        sys_data.en_wifi = 1;                                  // 网络功能使能
        sys_data.en_card_crypto = 1;                           // 卡片加密使能
        sys_data.openDirection = 0;                            //左开门 1 右开门 2
        sys_data.torsion = DEFAULT_OPEN_DOOR_POWER;            //低扭力 1 高扭力 2
        sys_data.amMode = DEFAULT_OPEN_LOCK_MODE;              //自动模式/手动模式（自动上锁/关闭自动上锁）
        #if defined(DEFAULT_AUTO_LOCK_TIME)
        sys_data.auto_lock_time = DEFAULT_AUTO_LOCK_TIME;      // 自动上锁时间(s)
        #endif
        sys_data.faceIsOpen = DEFAULT_FACE_FUNC;               //人脸功能默认关闭
        sys_data.en_handle = DEFAULT_TOUCH_HANDLE_FUNC;        //感应把手默认开启
        sys_data.hoverAlarmIsEable = DEFAULT_HOVER_ALARM_FUNC; //徘徊报警默认打开
        sys_data.hoverAlarmLevel = DEFAULT_HOVER_ALARM_LEVEL;  //徘徊等级中
        sys_data.touchKeyLockCnt = 0;                          //独立上锁键按下次数
        memset(sys_data.pcbaSn, 0, 32);                        // 产测使用的32字节SN
        memset(sys_data.model, 0, 20);
        memcpy(sys_data.model, LOCK_MODEL, sizeof(LOCK_MODEL)); // 产品型号
                                                                // for 5011
                                                                // uint8_t blekey[12] = {0x9F,0xA5,0x08,0x76,0xCB,0x2E,0xCE,0x93,0x61,0x02,0xE4,0xA6};//for 5011
                                                                // uint8_t esn[13] = "G590220710001";//01 ouweifeng    04 zengling
                                                                //		 uint8_t blekey[12] = {0x12,0x08,0xA9,0xF4,0x19,0x89,0x90,0x5E,0x96,0x98,0xD0,0x9E};
                                                                //		 uint8_t esn[13] = "G590220710004";
                                                                //		 memcpy(sys_data.bleKey, blekey, 12);
                                                                //		 memcpy(sys_data.eSN, esn, 13);
#if defined(WIFI_SUB_DEVICE)
        memset(sys_data.mqtt_domain, 0, sizeof(sys_data.mqtt_domain));
        memcpy(sys_data.mqtt_domain, "mqtt.kaadas.com", 15);
        sys_data.mqtt_port = 1883;
#endif
        // for 5011
        OSAL_NvWrite(0, &sys_data, sizeof(NvSystemParam_stu_t));
        SYS_CALL(Record_Delete);                           //删除所有记录
        SYS_CALL(Users_Del, 0XFF, 0XFF, NULL, 0);          //删除所有用户
        SYS_CALL(Face_Delete_Start, 0, 0xFF);              //删除全部人脸
        Finger_DeleteImage(0, KOS_PARAM_USERS_QTY_FINGER); //删除所有指纹模板
        SYS_CALL(Face_Factory);                            //删除所有人脸模板
        Audio_SetVolume(100);                              //音量设置成100
        Audio_SetLanguage(sys_data.default_language);      //设置默认语言
        Audio_SetMuteMode(RESET);                          //语音模式
        SYS_CALL(dsensor_set_sensitivity, DSENSOR_SENS_H); //设置默认的传感器灵敏度
        SYS_CALL(Face_Factory);                            //删除所有人脸模板
        Ble_Encryptionflag(0);
	    SYS_CALL(MC60_Del_All_Nfc);
    }

    if (reset == 1 || reset == 2)
    {
        NvSystemParam_stu_t sys_data = {0};
        sys_data.sys_flag = 0;                                 // 状态标志（bit0:防撬报警 bit1:布防报警 bit2:布防状态 bit3:反锁状态…… ）
        memset(sys_data.blekey2, 0, 4);                        // 蓝牙key2
        sys_data.powerSavingMode = POWER_SAVING_CLOSE;         // 节能模式
        sys_data.amMode = DEFAULT_OPEN_LOCK_MODE;              //自动模式/手动模式（自动上锁/关闭自动上锁）
        #if defined(DEFAULT_AUTO_LOCK_TIME)
        sys_data.auto_lock_time = DEFAULT_AUTO_LOCK_TIME;      // 自动上锁时间(s)
        #endif
        sys_data.videoIsOpen = DEFAULT_VIDEO_FUNC;             //视频功能是否开启 默认关闭
        sys_data.faceIsOpen = DEFAULT_FACE_FUNC;               //人脸功能是否开启 默认关闭
        sys_data.en_handle = DEFAULT_TOUCH_HANDLE_FUNC;        //感应把手使能
        sys_data.hoverAlarmIsEable = DEFAULT_HOVER_ALARM_FUNC; //徘徊报警使能
        sys_data.hoverAlarmLevel = DEFAULT_HOVER_ALARM_LEVEL;  //徘徊报警等级
        sys_data.default_language = DEFAULT_LANGUAGE;          //默认语言
        sys_data.touchKeyLockCnt = 0;                          //独立上锁键按下次数 //触摸上锁键按下计数值
        sys_data.verifyErrCount = 0;                           // 验证失败的次数
        sys_data.verifyErrTime = 0;                            // 验证失败的时间
        sys_data.systemLockedTime = 0;                         // 系统锁定的时间
        sys_data.openLockTimes = 0;                            // 开锁次数
        // sys_data.reserve[62];				    // 保留
        OSAL_NvWrite(SYS_OFFSET(sys_flag), &sys_data.sys_flag, SYS_OFFSET(reserve) - SYS_OFFSET(sys_flag));
        SYS_CALL(Record_Delete);                           //删除所有记录
        SYS_CALL(Users_SetSafeMode, RESET);                //删除所有用户
        SYS_CALL(Users_Del, 0XFF, 0XFF, NULL, 0);          //删除所有用户
        SYS_CALL(Face_Delete_Start, 0, 0xFF);              //删除全部人脸
        SYS_CALL(Face_Factory);                            //删除所有人脸模板
        Finger_DeleteImage(0, KOS_PARAM_USERS_QTY_FINGER); //删除所有指纹模板
        Audio_SetVolume(100);                              //音量设置成100
        Audio_SetMuteMode(RESET);                          //语音模式
        Audio_SetLanguage(sys_data.default_language);      //设置默认语言
        SYS_CALL(dsensor_set_sensitivity, DSENSOR_SENS_H); //设置默认的传感器灵敏度
        SYS_CALL(Remote_SetLanguage, DEFAULT_LANGUAGE);
        SYS_CALL(Remote_FactoryReset);
        Ble_Encryptionflag(0);
	    SYS_CALL(MC60_Del_All_Nfc);
        LOCAL_MAIN_LOG("NV Reset\r\n");
        Local_LockSaveRecord(EVENT_TYPE_PROGRAM, 0XFF, EVENT_CODE_RESTORE, 0XFF);

        Audio_Play(ZHI_WEN_YIN_DO, SET);
        Audio_Play(YI_HUI_FU_DAO_CHU_CHANG_SHE_ZHI, RESET);
        Audio_Play(MI_MA_GUO_YU_JIAN_DAN, RESET);
        Audio_Play(QING_XIU_GAI_GUAN_LI_MI_MA, RESET);
        if(reset == 1)//1:要重启   2：不要重启
        {
            if (DEFAULT_LANGUAGE == LANGUAGE_KAZAK) //哈萨克语言说的比较慢 多等一会
            {
                OSAL_SystemReset(10000);
            }
            else
            {
                OSAL_SystemReset(3000);
                LOCAL_MAIN_LOG("\r\n\r\nOSAL_SystemReset\r\n");
            }
        }
    }
    uint8_t verifyErrCount = 0;
    OSAL_NvRead(SYS_OFFSET(verifyErrCount), &verifyErrCount, sizeof(verifyErrCount));
    if (verifyErrCount >= VERIFY_FAIL_NUM)
    {
        uint32_t timestamp = 0;
        OSAL_TimeGet((uint8_t *)&timestamp, T_UTC);
        OSAL_NvWrite(SYS_OFFSET(systemLockedTime), &timestamp, sizeof(timestamp));
    }

    uint8_t lockMode = 0;
    OSAL_NvRead(SYS_OFFSET(amMode), &lockMode, sizeof(lockMode));
    Lock_ModeSync(lockMode);

    // verifyErrCount = FUNC_CODE;
    // OSAL_NvWrite(SYS_OFFSET(func_code), &verifyErrCount, sizeof(verifyErrCount));
    return SUCCESS;
}

/**
 * @brief 获取静默复位标志位
 *
 * @return uint8_t  SilentRest_flag
 *
 * @note
 */
static uint8_t Get_SilentRest_flag(void)
{
    uint8_t resetSilence = 0; //静默复位
    OSAL_NvRead(SYS_OFFSET(resetSilence), &resetSilence, 1);
    LOCAL_MAIN_LOG("resetSilence:%d\r\n", resetSilence);
    return resetSilence;
}
/**
 * @brief 设置静默复位标志位
 *
 * @param [in] flag
 *
 * @note
 */
static void Set_SilentRest_flag(uint8_t flag)
{
    uint8_t resetSilence = flag; //静默复位
    OSAL_NvWrite(SYS_OFFSET(resetSilence), &resetSilence, 1);
}
/**
 * @brief  BUTTON组件消息回调
 * @note
 *
 * @param  msg 消息指针
 * @param  len 消息数据长度
 * @return void
 */
static void Local_ButtonMsgCb(void *msg, uint16_t len)
{
    static uint8_t open_press_flag = false;
    ButtonMsg_t *button = (ButtonMsg_t *)msg;
    LOCAL_MAIN_LOG("button_msg_callback, %s, %d, %d\r\n", button->name, button->action, button->times);
    if (strcmp("BUT_RESET", button->name) == 0) //恢复出厂设置
    {
        if (button->action == USER_ACTION_LONG_PRESS) //恢复出厂设置
        {
            SYS_CALL(MC60_Send_Reset_Cmd);
            Local_NvReset(1);
        } 
        else if (button->action == INPUT_PORT_STA_RELEASE && button->times == 0)
        {
         if (Menu_GetCurrentMenu() == MENU_MASTER)
         {
           Led_Set("LED", LED_ON, 0, 0);
           asteriskKeyTimes = 2; 
           Audio_SetNotMute(ENTER_MANAGE_NOMUTE_FLAG,SET);
           Audio_Play(QING_YAN_ZHENG_GUAN_LI_YUAN_MI_MA, RESET);
           Audio_Play(YI_KAI_SUO_JIAN_JIE_SHU, RESET);
         }
        }
    }
    else if (strcmp("BUT_OPEN", button->name) == 0) //开门键
    {
        if (button->action == USER_ACTION_PRESS)
        {
            open_press_flag = true;
        }
        else if (button->action == INPUT_PORT_STA_RELEASE)
        {
            open_press_flag = false;
        }
#if defined(DOUBLE_CLICK_OPENDOOR)
        if (button->action == USER_ACTION_PRESS && button->times == 1) //双击开门
#else
        if (button->action == INPUT_PORT_STA_RELEASE && button->times == 0) //单击开门
#endif
        {
            Local_LockControl(USERS_TYPE_OPEN_KEY, USERS_ID_SIGNAL, LOCK_CTRL_UNLOCK);
            Audio_Play(AN_JIAN_YIN_DI, SET);
        }
        // Local_TouchHandleProcess(TOUCH_HANDLE_OPEN, button->action);
    }
    else if (strcmp("BUT_CLOSE", button->name) == 0) //上锁键
    {
        if (button->action == INPUT_PORT_STA_RELEASE && button->times == 0) //开关锁键
        {
            LOCAL_MAIN_LOG("close button locked \r\n");
           Local_LockControl(USERS_TYPE_KEY, 0xFF, LOCK_CTRL_VERIFY_OK);
        }
        // Local_TouchHandleProcess(TOUCH_HANDLE_CLOSE, button->action);
    }
    else if (strcmp("HOME_KEY", button->name) == 0) //Homekit键
    {
        if (button->action == INPUT_PORT_STA_RELEASE && button->times == 0)
        {
            LOCAL_MAIN_LOG("HOME_KEY \r\n");
           SYS_CALL(MC60_Send_Homekit_Pair);
        } 
    }
    
    // else if (strcmp("BUT_TOUCH1", button->name) == 0)
    // {
    //     Local_TouchHandleProcess(TOUCH_HANDLE_PAD1, button->action);
    // }
    // else if (strcmp("BUT_TOUCH2", button->name) == 0)
    // {
    //     Local_TouchHandleProcess(TOUCH_HANDLE_PAD2, button->action);
    // }
    else if (strcmp("BUT_DAMAGE", button->name) == 0) //防撬开关
    {
        __EFRAM static uint8_t openOnFlag = 0;
        __EFRAM static uint8_t releasStatu = RESET;
        if (button->action == USER_ACTION_LONG_PRESS)
        {
            if (openOnFlag == 0 && releasStatu == SET) //检测到松开且第一次检测到防撬异常则报警
            {
                // openOnFlag = 1;
                LocalSub_SetAlarm(true, ALARM_TYPE_FORCE_UNLOCK); //设置防撬报警
            }
        }
        else if (button->action == USER_ACTION_RELEASE)
        {
            releasStatu = SET; //标记防撬开关被按下过（上电没按下过直接检测到松开不生效）
        }
    }
    else if (strcmp("BUT_COVER_CHECK", button->name) == 0) //滑盖
    {
#ifdef COVER_CHECK
        __EFRAM static uint8_t poweronflag = 0;
        __EFRAM static uint8_t coverIsCheckFlag = 0;
        if (button->action == USER_ACTION_PRESS)
        {
            if (poweronflag != 0)
            {
                Led_Set("LED", LED_ON, 0, 0);
                Audio_Play(HUAN_YING_YIN, RESET);
                coverIsCheckFlag = 1;
            }

            poweronflag = 1;
        }
        else if (button->action == USER_ACTION_RELEASE)
        {
            if (poweronflag != 0)
            {
                if (coverIsCheckFlag == 1)
                {
                    Led_Set("LED", LED_OFF, 0, 0);
                }
                coverIsCheckFlag = 0;
            }
        }
#endif
    }
    // else if (strcmp("BUT_M_KEY", button->name) == 0) //机械钥匙   524锁体 机械钥匙报警放到锁体组件了
    // {
    //     if (button->action == USER_ACTION_PRESS)
    //     {
    //         LocalSub_SetAlarm(true, ALARM_TYPE_MECH_UNLOCK); //设置机械钥匙报警
    //     }
    // }
    OSAL_UpdateSleepTime(AUTO_SLEEP_TIME, 1);
}

/**
 * @brief  播放门铃
 * @note
 * @param
 * @return
 */
static void Local_PlayDoorbell(uint8_t report)
{
    static uint32_t last_time = 0;
    uint32_t cur_time = OSAL_GetTickCount();
    if (cur_time < 1000 || cur_time - last_time > 1000)
    {
        last_time = cur_time;
        Led_Set("LED_PWM_B", LED_ON, 0, 0);
        Audio_PlayDoorbell(HUAN_YING_YIN, 2);
        if (report)
        {
            SYS_CALL(Remote_DoorBellNotify);
        }
    }
}

static uint8_t g_ignoreKeyReleasedMsgFlag = 0;
static uint8_t g_LedONFlag = 1;
/**
 * @brief  丢弃触摸抬起消息
 * @note
 * @return
 */
void Local_IgnoreTouchReleasedMsg(void)
{
    g_ignoreKeyReleasedMsgFlag = 1;
}

/**
 * @brief  TOUCH组件消息回调
 * @note
 *
 * @param  msg 消息指针
 * @param  len 消息数据长度
 * @return void
 */
static void Local_TouchMsgCb(void *msg, uint16_t len)
{
    TouchMsg_t *touch = (TouchMsg_t *)msg;
    MenuType_enum_t menu = Menu_GetCurrentMenu();
    if (msg == NULL || len == 0)
    {
        LOCAL_MAIN_LOG("msg is null\r\n");
        return;
    }
    LOCAL_MAIN_LOG("Local_TouchMsgCb, action :%d,keyNum: %c,times: %d\r\n", touch->action, touch->keyNum, touch->times);
    if (touch->keyNum != 'D')
    {
        if (touch->action == USER_ACTION_RELEASE)
        {
            //if (!(g_ignoreKeyReleasedMsgFlag && touch->keyNum == '#'))
            if (!g_ignoreKeyReleasedMsgFlag)
            {
                Led_Set("LED", LED_ON, 0, 0);
                g_LedONFlag = 1;
                //LOCAL_MAIN_LOG("Led 02");
                if (Menu_GetCurrentMenu() == MENU_MASTER)
                {
                    Led_Set("LED_LOCK", LED_ON, 0, 0);
                }
            }
            g_ignoreKeyReleasedMsgFlag = 0;
        }
        else if (touch->action == USER_ACTION_PRESS)
        {
            uint8_t led[5] = {0X4C, 0X45, 0X44, 0X00, 0X00};
            led[3] = touch->keyNum;
            Led_Set((char *)led, LED_OFF, 0, 0);
            if (touch->keyNum != 'L') //如果触摸按键不等于独立上锁键
            {
                Audio_Play(AN_JIAN_YIN_DI, SET);
                Beep_Set(1, 100); //响一声
                if (LocalSub_CheckZeroKeyEnterArming(touch->keyNum) != true)
                {
                    Menu_UserInputProcess(INPUT_TYPE_CHAR, (uint8_t *)&touch->keyNum, 1); //菜单处理
                }
                if (touch->keyNum == '#')
                {
                    uint8_t time[6];
                    OSAL_TimeGet(time, T_TIME);
                    LOCAL_MAIN_LOG("time:%04d-%02d-%02d %02d:%02d:%02d", time[0] + 2000, time[1], time[2], time[3], time[4], time[5]);
                    LOCAL_MAIN_LOG("MiniFreeHeapSize:%d Bytes\r\n", OSAL_GetMinimumEverFreeHeapSize());
                }
                else if (touch->keyNum == '*') //关锁按键
                {
                    if (Menu_GetCurrentMenu() == MENU_MASTER)
                    {
                        Local_LockControl(LOCKED_OUTDOOR, 0, LOCK_CTRL_LOCKED_KEY);  // 关锁键关锁，id编号为0
                        Led_Set("LED", LED_OFF, 0, 0); 
                        if(g_LedONFlag == 1)
                        {
                            Local_IgnoreTouchReleasedMsg();
                            g_LedONFlag = 0;
                        }
                        //LOCAL_MAIN_LOG("Led 01"); 
                    }
                }
            }
            else //门外独立上锁键
            {
                if (menu == MENU_MASTER && (Local_LockGetTouchKeyLockTime() <= 5)) //主菜单下才可以设置语音模式
                {
                    Audio_Play(AN_JIAN_YIN_DI, SET);
                    Beep_Set(1, 100); //响一声
                    Local_LockControl(0XFF, 0XFF, LOCK_CTRL_LOCKED);
                }
                else if (menu == MENU_MASTER && (Local_LockGetTouchKeyLockTime() > 5))
                {
                    Audio_Play(AN_JIAN_YIN_DI, SET);
                }
                Led_Set("LED_LOCK", LED_OFF, 0, 0);
            }
        }
        //else if (touch->action == USER_ACTION_LONG_PRESS) //按键长按
        //{
            // if (touch->keyNum == '0') //复用0号键做静音设置
            // {
            //     if (menu == MENU_MASTER) //主菜单下才可以设置语音模式
            //     {
            //         uint8_t audioMode = RESET;
            //         audioMode = Audio_GetMuteMode();
            //         if (audioMode == SET) //静音状态下 播报语音模式
            //         {
            //             Audio_SetMuteMode(RESET);
            //             Audio_Play(YU_YIN_MO_SHI, SET);
            //             Oled_PopUpDisplay(POPUPS_VoicePromptOn, POPUPS_NULL, POP_UP_WINDOW_TIME);
            //         }
            //         else //语音模式下 播报静音模式
            //         {
            //             Audio_Play(JING_YIN_MO_SHI, SET);
            //             Audio_SetMuteMode(SET);
            //             Oled_PopUpDisplay(POPUPS_VoicePromptOff, POPUPS_NULL, POP_UP_WINDOW_TIME);
            //         }
            //         SYS_CALL(Remote_SettingChangeReport);
            //         LOCAL_MAIN_LOG("audioMode :%d\r\n", audioMode);
            //     }
            // }
            // if (Menu_GetCurrentMenu() == MENU_MASTER)
            // {
            //     Local_LockControl(USERS_TYPE_UNKNOW, 0, LOCK_CTRL_LOCKED);  // 长按关锁，id编号为0  
            // }
        //}
    }
    else //门铃按键
    {
        if (touch->action == USER_ACTION_PRESS)
        {
            Local_PlayDoorbell(1);
        }
    }
    LocalSub_SetAlarm(false, ALARM_TYPE_LOCK_ABNORMAL); //取消锁体异常报警
    LocalSub_ExitStartArming();
    OSAL_UpdateSleepTime(AUTO_SLEEP_TIME, 1);
}

/**
 * @brief  指纹组件消息回调
 * @note
 *
 * @param  msg 消息指针
 * @param  len 消息数据长度
 * @return void
 */
static void Local_FingerMsgCb(void *msg, uint16_t len)
{
    FingerMsg_t *finger = (FingerMsg_t *)msg;
    const MenuType_enum_t menu = Menu_GetCurrentMenu();
    LOCAL_MAIN_LOG("Local_FingerMsgCb action :%02X menu:%02X \r\n", finger->action, menu);
    if (menu != MENU_MASTER && menu != MENU_ADD_FPT && menu != MENU_DEL_FPT && menu != MENU_DEL_ALL_FPT && menu != MENU_DEL_PWD)
    {
        return;
    }
    switch (finger->action)
    {
    case FINGER_ACTION_GET_IMAGE_OK:
        Audio_Play(ZHI_WEN_YIN_DO, SET);
        // local_CancelFaceVerifyFlow(0);
        LocalSub_SetAlarm(false, ALARM_TYPE_LOCK_ABNORMAL); //取消锁体异常报警
        LocalSub_ExitStartArming();
        break;
    case FINGER_ACTION_ENTER_AGAIN:
        Audio_Play(QING_NA_KAI_SHOU_ZHI_ZAI_AN_YI_CI, RESET);
        break;
    case FINGER_ACTION_VERIFY_OK:
    case FINGER_ACTION_ADD_OK:
        Menu_UserInputProcess(INPUT_TYPE_FP, &finger->fingerNumber, 1);
        break; //菜单处理
    case FINGER_ACTION_VERIFY_ERR:
    case FINGER_ACTION_ADD_ERR:
        finger->fingerNumber = 0XFF;
        Menu_UserInputProcess(INPUT_TYPE_FP, &finger->fingerNumber, 1);
        break; //菜单处理
    default:
        break;
    }
    OSAL_UpdateSleepTime(AUTO_SLEEP_TIME, 1);
}

/**
 * @brief  卡片组件消息回调
 * @note
 *
 * @param  msg 消息指针
 * @param  len 消息数据长度
 * @return void
 */
static void Local_CardMsgCb(void *msg, uint16_t len)
{
    CardMsg_t *card = (CardMsg_t *)msg;

    MenuType_enum_t menu = Menu_GetCurrentMenu();
    LOCAL_MAIN_LOG("Local_CardMsgCb menu :%02X card len :%d\r\n", menu, card->cardLen);
    if ((menu != MENU_MASTER && menu != MENU_ADD_CARD && menu != MENU_DEL_CARD) || card->cardLen == 0)
    {
        return;
    }
    // local_CancelFaceVerifyFlow(0);
    LocalSub_SetAlarm(false, ALARM_TYPE_LOCK_ABNORMAL); //取消锁体异常报警
    LocalSub_ExitStartArming();
    Audio_Play(ZHI_WEN_YIN_DO, SET);
    Menu_UserInputProcess(INPUT_TYPE_CARD, card->cardId, card->cardLen);
    OSAL_UpdateSleepTime(AUTO_SLEEP_TIME, 1);
}

static void Local_BatteryCb(void *msg, uint16_t len)
{
    uint8_t bat = SYS_CALL(Battery_Get);
    uint16_t batVoltage = SYS_CALL(Battery_VoltageGet);
    LOCAL_MAIN_LOG("Battery updata :%d\r\n", bat);
    Menu_UpdateBattery(bat);
    if (Get_SilentRest_flag() == SET)
        return;
    if (SYS_CALL(Battery_Get) <= BATTERY_LOW_POWER_II)
    {
        Led_Set("LED_BAT", LED_OFF, 0, 0);
        Led_Set("LED_LP", LED_FLASH, 0xff, 1000);
    }
    else
    {
        Led_Set("LED_BAT", LED_ON, 0, 0);
        Led_Set("LED_LP", LED_OFF, 0, 0);
    }
    Lock_SetBatVolt(batVoltage);

}

/**
 * @brief  user组件消息回调
 * @note   紧急（胁迫）用户开锁报警
 *
 * @param  msg 消息指针
 * @param  len 消息数据长度
 * @return void
 */
static void Local_UsersCb(void *msg, uint16_t len)
{
    uint8_t user_id = ((UsersMsg_t *)msg)->ID;
    Local_LockSaveRecord(EVENT_TYPE_ALARM, USERS_TYPE_PWD, EVENT_CODE_HIJACK, user_id); //这里要改  密钥类型要加多一个指纹  暂时先这样
}

static void Local_AudioCb(void *msg, uint16_t len)
{
    uint16_t number = ((AudioPublishMsg_t *)msg)->number;

    LOCAL_MAIN_LOG("audio end:%d\r\n", number);
    // 在管理菜单下：每句话播放完都刷新时间（防止太快退出管理菜单）
    if (Menu_GetCurrentMenu() != MENU_MASTER)
    {
        OSAL_UpdateSleepTime(AUTO_SLEEP_TIME, 1);
    }
    Menu_PlayMenuAudioList(number);
}

/**
 * @brief  APP休眠回调
 * @note
 *
 * @param
 * @param
 * @return
 */
static ErrorStatus Local_SleepCb(void)
{
    ErrorStatus status = ERROR;
    LOCAL_MAIN_LOG("local_main Local_SleepCb\r\n");
    MenuType_enum_t menu = Menu_GetCurrentMenu();
    uint8_t fpt_flag = 0;
    if (menu != MENU_MASTER)
    {
        {
            Menu_SwitchMenu(MENU_MASTER);
            Led_Set("LED", LED_OFF, 0, 0);
        }
    }
    else if (LocalSub_CheckAlarmStatus() == true)
    {
        LOCAL_MAIN_LOG("Sleep failed, Alarming...\r\n");
    }
    else if (Local_LockGetAutoLockTimer() != NULL)
    {
        LOCAL_MAIN_LOG("Sleep failed, Door is not lock\r\n");
    }
    else if (Lock_SleepProcess() != SUCCESS)
    {
        LOCAL_MAIN_LOG("Sleep failed, lock process busy\r\n");
    }
    else
    {
        fpt_flag = get_fpt_sleep_flag();
        if(fpt_flag == 0)
        {
            Finger_send_cmd_pack(0X33, NULL, 0); //  PS_SLEEP 睡眠指令
            set_fpt_sleep_flag(1);
            OSAL_UpdateSleepTime(1000, 1);
            //LOCAL_MAIN_LOG("fpt_sleep_flag 001\r\n");
            return ERROR;
        }

        LOCAL_MAIN_LOG("System sleep\r\n");
        Led_Set("LED", LED_OFF, 0, 0);
        Led_Set("LED_LP", LED_OFF, 0, 0);
        Led_Set("LED_LOCK", LED_OFF, 0, 0);
        Audio_SetNotMute(ENTER_MANAGE_NOMUTE_FLAG,RESET);
        return SUCCESS;
    }
    OSAL_UpdateSleepTime(1000, 1);//
    return status;
}

/**
 * @brief  同步RTC
 * @note   以最近一次事件记录的时间同步RTC
 *         记录为空时，同步成2021/01/01 00:00:00
 */
static void local_sync_rtc(void)
{
    uint32_t default_time = 1609459200; // 2021/01/01 00:00:00
    uint32_t record_time = SYS_CALL(Record_GetLastTimestamp);
    uint32_t rtc = 0;

    OSAL_TimeGet(&rtc, T_UTC);
    if (rtc < record_time || rtc < default_time)
    {
        LOCAL_MAIN_LOG("local_sync_rtc:%ld, %ld, %ld\n", rtc, record_time, default_time);
        rtc = (record_time > default_time) ? record_time : default_time;
        OSAL_TimeSet(&rtc, T_UTC);
    }
    else
    {
        LOCAL_MAIN_LOG("local_sync_rtc:%ld\n", rtc);
    }
}

/**
 * @brief  唤醒处理
 * @note
 */
void local_WakeUpProcess(uint32_t wakeup_id, uint8_t param)
{
    if (wakeup_id == COMP_TOUCH && (param == 1 || param == 4)) //触摸唤醒 不是门铃唤醒
    {
        Led_Set("LED_PWM_B", LED_ON, 0, 0);
        {
            Led_Set("LED", LED_ON, 0, 0);
            g_LedONFlag = 1;
        }
    }
    else if (wakeup_id == COMP_TOUCH && param == 2) //触摸唤醒 是门铃唤醒
    {
        Local_PlayDoorbell(0);
    }
    else if (wakeup_id == COMP_BUTTON && param == vPIN_B15) //滑盖
    {
        Led_Set("LED", LED_ON, 0, 0);
    }
    if (wakeup_id == 0XFF) //上电唤醒
    {
        uint8_t touchKeyLockCnt = 0;
        OSAL_NvRead(SYS_OFFSET(touchKeyLockCnt), &touchKeyLockCnt, sizeof(touchKeyLockCnt));
        if (touchKeyLockCnt != 6)
        {
            touchKeyLockCnt = 0;
            OSAL_NvWrite(SYS_OFFSET(touchKeyLockCnt), &touchKeyLockCnt, sizeof(touchKeyLockCnt));
        }
        Audio_Play(HUAN_YING_YIN, RESET);
    }

    if (wakeup_id == COMP_TOUCH && param == 1 || wakeup_id == 0XFF)
    {
        uint8_t activedStatu = SYS_CALL(Users_IsLockActived, NULL);

        if (SYS_CALL(Users_AdminPwdIsEasy) == true && activedStatu == SUCCESS)
        {
            // if ((Local_LockGetLockType() == LOCK_TYPE_BW && Menu_GetOpenDoorDirection() != 0) || Local_LockGetLockType() != LOCK_TYPE_BW)
            // {
            //     Audio_Play(MI_MA_GUO_YU_JIAN_DAN, RESET);
            //     Audio_Play(QING_XIU_GAI_GUAN_LI_MI_MA, RESET);
            // }
        }
    }

    uint8_t esn[13] = {0};
    OSAL_NvRead(SYS_OFFSET(eSN), esn, 13);
    LOCAL_MAIN_LOG("ESN :%s\r\n", esn);

    if (Local_LockGetLockType() == LOCK_TYPE_DAI)
    {
        // 呆锁自动上锁唤醒检测
        Local_LockProcessWakeSrc(wakeup_id);
    }

    if (wakeup_id == COMP_XUNMEI)
    {
        OSAL_UpdateSleepTime(5000, 1);
    }
    else
    {
        OSAL_UpdateSleepTime(AUTO_SLEEP_TIME, 1);
    }
}

/**
 * @brief  读取系统标志
 * @note
 *
 * @param  flag：SYS_FLAG_TAMPER_ALARM 防撬报警标志
 *               SYS_FLAG_ARMING_ALARM 布防报警标志
 *               SYS_FLAG_ARMING_STATUS 布防状态
 *               SYS_FLAG_ANTI_LOCK_STATUS 反锁状态
 *
 * @return state：标志状态 true 和 false
 */
static bool Local_GetSysFlag(uint8_t flag)
{
    uint8_t sys_flag = 0;
    OSAL_NvRead(SYS_OFFSET(sys_flag), &sys_flag, 1);
    uint8_t test = 0;
    test = sys_flag & flag;
    LOCAL_MAIN_LOG("sys_flag :%02X,test:%02X\r\n", sys_flag, test);
    return (sys_flag & flag) ? true : false;
}

static TimerHandle_stu_t TimerHandle_SetSilentRest = NULL;
/**
 * @brief 清除静默复位标志位回调
 *
 * @param [in] xTimer
 *
 * @note
 */
static void Clear_SilentRest_Callback(TimerHandle_stu_t xTimer)
{
    LOCAL_MAIN_LOG("Clear_SilentRest\r\n");
    Set_SilentRest_flag(RESET);
}
/**
 * @brief  local APP启动函数
 * @note
 *
 * @param  wake_id：唤醒ID（组件ID），0XFF表示上电唤醒
 * @param  wake_param：唤醒参数
 */
static void Local_Main(uint32_t wake_id, uint32_t wake_param)
{
    uint8_t verifyFailCount = 0;
    LOCAL_MAIN_LOG("local_main, wake_id:%ld, wake_param:%ld\r\n", wake_id, wake_param);
    if (wake_id == 0XFF)
    {
        //上电唤醒：创建APP，订阅消息
        uint8_t version[10] = {0};
        Audio_GetVersion(version);
        LOCAL_MAIN_LOG("audioVer: %s\r\n", version);
        memset(version, 0, sizeof(version));
        DFU_GetVersion(DFU_DEVNUM_REAR_MCU, version);
        LOCAL_MAIN_LOG("rearbord version: %s\r\n", version);

        Local_NvReset(0);
        Finger_WorkModeSet(FINGER_WORK_MODE_VERIFY, 0);

        if (Get_SilentRest_flag() != SET)
        {
            Beep_Set(1, 500); //上电先响一声
            Local_LockControl(0XFF, 0XFF, LOCK_CTRL_LOCKED);
            Led_Set("LED", LED_ON, 0, 0);
        }
        OSAL_NvWrite(SYS_OFFSET(verifyErrCount), &verifyFailCount, sizeof(verifyFailCount)); 
    }
    if (Get_SilentRest_flag() == SET)
    {
        TimerHandle_SetSilentRest = OSAL_TimerCreate(Clear_SilentRest_Callback, 2000, RESET);
    }
    AppHandle_t app_handle = OSAL_AppCreate("APP_LOCAL", Local_SleepCb);
    OSAL_MessageSubscribe(app_handle, COMP_BUTTON, Local_ButtonMsgCb);
    //OSAL_MessageSubscribe(app_handle, COMP_CARD, Local_CardMsgCb);//--------
    OSAL_MessageSubscribe(app_handle, COMP_FINGER, Local_FingerMsgCb);
    OSAL_MessageSubscribe(app_handle, COMP_TOUCH, Local_TouchMsgCb);
    OSAL_MessageSubscribe(app_handle, COMP_BATTERY, Local_BatteryCb);
    OSAL_MessageSubscribe(app_handle, COMP_USERS, Local_UsersCb);
    OSAL_MessageSubscribe(app_handle, COMP_AUDIO, Local_AudioCb);
    SYS_API(Local_GetSysFlag);
    SYS_API(Set_SilentRest_flag);
    Local_LockInit(app_handle);
    local_sync_rtc();
    Menu_UpdateSysLanguage(Audio_GetLanguage());
    LocalSub_Init(&local_sub_timer);
    local_WakeUpProcess(wake_id, wake_param);
    Menu_Init(wake_id);
    uint8_t bat = SYS_CALL(Battery_Get);
    Menu_UpdateBattery(bat);
}
APP_INIT_EXPORT(Local_Main);
